package com.inspur.edp.cef.repository.extend;

import com.inspur.edp.cef.repository.exception.CefRepositoryException;
import com.inspur.edp.cef.spi.repository.BaseDbColumnInfo;
import com.inspur.edp.cef.spi.repository.FieldContext;
import com.inspur.edp.cef.spi.repository.IFieldReposExtendProcessor;
import com.inspur.edp.cef.repository.adaptor.KeyWordsManager;

/**
 * @Author wangmaojian
 * @create 2023/4/17
 */
public class BuiltInFieldProcessor implements IFieldReposExtendProcessor {
    @Override
    public String getQueryField(FieldContext fieldContext) {
        StringBuilder columns = new StringBuilder();
        BaseDbColumnInfo columnInfo = fieldContext.getDbColumnInfo();
        String columnName = trans2DbColumnWithAlias(columnInfo, fieldContext);
        columns.append(columnName).append(" AS ").append(columnInfo.getAliasName(fieldContext.getIndex()));

        return columns.toString();
    }

    private String getAssociateDbColumnName(BaseDbColumnInfo columnInfo) {
        if (columnInfo.getDbColumnName() == null || columnInfo.getDbColumnName().length() == 0) {
            throw new CefRepositoryException("尚未获取关联引用字段数据库列名称，请先获取引用字段");
        }
        return columnInfo.getDbColumnName();
    }

    private String trans2DbColumnWithAlias(BaseDbColumnInfo columnInfo, FieldContext fieldContext){
        if(columnInfo.getIsAssociateRefElement()){
            //todo 带出字段如果是多语字段？
            return getAssociateDbColumnName(columnInfo);
        }
        String dbName = KeyWordsManager.getTableAlias(fieldContext.getTableAlias()) + "." + KeyWordsManager.getColumnAlias(columnInfo.getDbColumnName());
        //检索启用多语，会单独再追加一下
        if (columnInfo.getIsMultiLang()) {
            dbName = dbName + "@Language@";
        }
        return dbName;
    }
}
